package com.lhg.file.controller;

import com.lhg.common.exception.BusinessException;
import com.lhg.common.page.ResultInfo;
import com.lhg.common.util.IDGenerator;
import com.lhg.file.entity.OAFile;
import com.lhg.file.service.OAFileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author fangzc
 * @date 2018/11/13 16:21
 */
@Controller
@RequestMapping(value = "/file")
public class OAFileController {

    private static Logger logger = Logger.getLogger(OAFileController.class);

    @Value("${file.root.path}")
    private String fileRootPath;

    @Resource
    private OAFileService oaFileService;

    @RequestMapping({"/download"})
    public void download(HttpServletRequest request, HttpServletResponse response, String fileId) {
        if (fileId == null) {
            throw new BusinessException("文件id不正确");
        }
        //得到要下载的文件
        OAFile file = oaFileService.getById(fileId);
        if (Objects.isNull(file)) {
            throw new BusinessException("文件不存在");
        }
        File targetFile = new File(this.fileRootPath, file.getFilePath());
        if (Objects.isNull(targetFile) || !targetFile.exists()) {//如果文件不存在
            throw new BusinessException("文件id不正确");
        }
        //处理文件名
        String realname = file.getFileName();
        //设置响应头，控制浏览器下载该文件
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = null;
        try {
            in = new FileInputStream(targetFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //创建输出流
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/upload")
    @ResponseBody
    public ResultInfo upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        return ResultInfo.success(savefile(file));
    }

    /**
     * 保存文件以及附件
     *
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public String savefile(MultipartFile file) throws IllegalStateException, IOException {
        /**
         * 1. 获取配置的上传文件系统绝对路径根目录
         * 2. 保存文件到此文件夹，文件夹生成规则为年月日各自一个文件夹，
         * 3. 保存文件名，文件相对路径，文件后缀名，文本类型，用户所属id,文件上传时间，文件大小，
         */
        File savepath = new File(this.fileRootPath, new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        if (!savepath.exists()) {
            savepath.mkdirs();
        }
        String shuffix = FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileName = UUID.randomUUID().toString().toLowerCase() + "." + shuffix;
        File targetFile = new File(savepath, newFileName);
        file.transferTo(targetFile);
        String fileId = IDGenerator.getGUID();
        OAFile oaFile = new OAFile();
        oaFile.setPkid(fileId);
        oaFile.setFileName(file.getOriginalFilename());
        oaFile.setFilePath(targetFile.getAbsolutePath().replace("\\", "/").replace(this.fileRootPath, ""));
        oaFile.setFileShuffix(shuffix);
        oaFile.setContentType(file.getContentType());
        oaFile.setSize(file.getSize());
        oaFile.setCreateUserId("");
        oaFile.setCreateDateTime(new Date());
        oaFileService.saveSelective(oaFile);
        return fileId;
    }
}
